﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

using Simple.CMS.Web.Areas.Admin.Models;
using Simple.CMS.Web.Repository;
using Simple.Common;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Simple.CMS.Web.Authorization;

namespace Simple.CMS.Web.Areas.Admin.Controllers
{
    /// <summary>
    /// 账户管理
    /// </summary>
    [Area("Admin")]
    public class AccountController : Controller
    {
        private readonly CmsContext _cmsContext;

        public AccountController(CmsContext cmsContext)
        {
            _cmsContext = cmsContext;
        }

        [Authorize]
        public IActionResult Index()
        {
            return View();
        }


        #region 登录

        [HttpGet]
        public IActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        public IActionResult Login(LoginModel model)
        {
            var u = _cmsContext.AdminUsers.FirstOrDefault(it => it.Email == model.LoginName);
            if (u == null)
            {
                return Json(new Result { Code = -1, Message = "用户名或密码错误" });
            }
            if (u.LockTime.HasValue && u.LockTime.Value > DateTime.Now)
            {
                var m = (u.LockTime.Value - DateTime.Now).Minutes;
                return Json(new Result { Code = -1, Message = $"账户锁定中，请{m}分钟后再试" });
            }
            var pwd = RsaHelper.Md5Encrypt(model.Password, u.Salt);
            if (pwd != u.Password)
            {
                u.PwdIncorrectTimes++;
                u.LastUpDateTime = DateTime.Now;
                if (u.PwdIncorrectTimes > 5)
                {
                    u.LockTime = DateTime.Now.AddMinutes(20);
                }
                _cmsContext.SaveChanges();
                return Json(new Result { Code = -1, Message = "用户名或密码错误" });
            }
            var ip = Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (ip.IsNullOrEmpty())
            {
                ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
            }
            u.LastLoginIp = ip;
            u.LastLoginTime = DateTime.Now;
            u.PwdIncorrectTimes = 0;
            u.LastUpDateTime = DateTime.Now;
            _cmsContext.SaveChanges();

            //授权信息
            /*
            var identity = new AdminIdentity ();
            identity.Roles.Add(u.Role.ToString());
            identity.UserId = u.Id;
            */
            var userData = new AuthorizationData{ DisplayName = u.DisplayName, HeadImg = u.HeadImg, LoginName = u.Email, Role = u.Role, UserId = u.Id};
            var list = new List<Claim>
            {
                new Claim(ClaimTypes.Role, u.Role.ToString()),
                new Claim(ClaimTypes.Email, u.Email),
                new Claim(ClaimTypes.Name, u.DisplayName),
                new Claim(ClaimTypes.NameIdentifier, u.Id.ToString()),
                new Claim(ClaimTypes.UserData, userData.ToJson())
            };

            var principal = Request.HttpContext.User;
            var identity = new ClaimsIdentity("DIY");
            identity.AddClaims(list);
            principal.AddIdentity(identity);

            Request.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
            return Json(new Result());
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public IActionResult Logoff()
        {
            //AuthorizeSession.SignOut(Request.HttpContext);
            return new EmptyResult();
        }
        #endregion

        #region 忘记密码

        [HttpGet]
        public IActionResult ForgetPassword()
        {
            return View();
        }


        [Authorize, HttpPost]
        public IActionResult ResetPassword()
        {
            return Json(null);
        }

        #endregion

    }
}